<?php

declare(strict_types=1);

namespace app\libs\alipay;

use Alipay\OpenAPISDK\ApiException;
use Alipay\OpenAPISDK\Util\AlipayConfigUtil;
use Alipay\OpenAPISDK\Util\AlipaySignature;
use Alipay\OpenAPISDK\Util\GenericExecuteApi;
use Alipay\OpenAPISDK\Util\Model\AlipayConfig;
use Alipay\OpenAPISDK\Util\Model\CustomizedParams;
use Alipay\OpenAPISDK\Util\Model\OpenApiGenericRequest;
use GuzzleHttp\Client;

/**
 * 封装常用支付宝功能
 * 依赖: composer require alipaysdk/openapi
 * @doc https://opendocs.alipay.com/open-v3
 */
class UseAlipay
{
	protected static $alipay;

	/**
	 * 获取Api客户端实例
	 * 多次获取只返回全局唯一单例
	 * @return GenericExecuteApi
	 */
	public static function getApiClient(): GenericExecuteApi
	{
		if (self::$alipay) return self::$alipay;

		// 初始化SDK
		$alipayConfigUtil = new AlipayConfigUtil(self::getAlipayConfig());

		$apiInstance = new GenericExecuteApi(
			$alipayConfigUtil,
			new Client()
		);

		self::$alipay = $apiInstance;
		return self::$alipay;
	}

	/**
	 * 验证通知参数签名
	 * @return boolean
	 * @throws Exception
	 */
	public static function verifyNotifySign($params)
	{
		$alipayPublicKey = config('alipay.AlipayPublicKey');
		return AlipaySignature::rsaCheckV1($params, $alipayPublicKey);
	}

	protected static function getAlipayConfig()
	{
		$configArray = config('alipay');

		$config = new AlipayConfig();
		foreach ($configArray as $key => $value) {
			$funcName = 'set' . ucfirst($key);
			$config->$funcName($value);
		}
		return $config;
	}
}
